import random
import time

import requests
from cacheout import Cache


def get_median_num(num_list: list):
    if num_list:
        num_list.sort()
        half = len(num_list) // 2
        return (num_list[half] + num_list[~half]) / 2


class WmProxy(object):
    def __init__(self):
        super().__init__()
        self.cache = Cache()
        self.current_retry_num = 0
        self.max_retry_num = 5
        self.last_refresh_time = time.time()
        self.refresh_interval_time = 3 * 60  # 获取ip代理默认间隔时间（秒）
        self._set_proxy_pool()
        self.username = "0bc97acc4de7"
        self.password = "00d8c8b17e"

    @staticmethod
    def _get_proxy_list():
        get_proxy_url = 'https://proxyapi.mimvp.com/api/fetchsecret.php?' \
                        'orderid=868366592412306492&num=15&http_type=3' \
                        '&result_fields=1,3,6&result_format=json'
        resp = requests.get(get_proxy_url).json()
        if resp:
            # print(resp)
            if resp["code"] == 0:
                return resp["result"]

    def _set_proxy_pool(self):
        proxy_list = self._get_proxy_list()
        if proxy_list:
            self.current_retry_num = 0
            avail_list = []
            for proxy in proxy_list:
                # band_with = int(proxy['bandwidth'])
                # if band_with < 10:
                #     print(f"带宽: {band_with} 太低, 舍弃")
                #     continue
                avail = int(proxy['time_avail'])
                self.cache.add(proxy["ip:port"], proxy["ip:port"], ttl=avail)
                avail_list.append(avail)
            else:
                self.last_refresh_time = time.time()
                self.refresh_interval_time = get_median_num(avail_list)
        else:
            self.current_retry_num += 1
            if self.current_retry_num >= self.max_retry_num:
                raise RuntimeError("获取代理的连续失败次数，超过允许的最大次数")
            else:
                self._set_proxy_pool()

    def _get_proxy_from_cache(self):
        key_list = list(self.cache.keys())
        if key_list and abs(time.time() - self.last_refresh_time) <= self.refresh_interval_time:
            i = random.randint(0, len(key_list))
            try:
                key = key_list[i]
                value = self.cache.get(key)
                # print(len(key_list), i, key, value)
                # self.cache.delete(key)
                if value:
                    return value
                else:
                    # print("value 为 None， 再次获取")
                    self._get_proxy_from_cache()
            except IndexError:
                # print("出现 indexError， 再次获取")
                self._get_proxy_from_cache()
        else:
            # print("缓存中空， 再次获取")
            self._set_proxy_pool()
            self._get_proxy_from_cache()

    def get_proxies(self):
        return {
            "http": f"http://{self.username}:{self.password}@{self._get_proxy_from_cache()}",
        }


if __name__ == "__main__":
    wp = WmProxy()
    v = wp.get_proxies()
    print(v)
